# coding=utf-8
from django.shortcuts import render_to_response
from django.core.exceptions import ObjectDoesNotExist
from apps.news.models import News
from apps.research.views import head_group
import datetime

MAX_ITEMS = 10   # 列表最大文章数，要改

# 新闻页面处理
def news(request, lang, news_id):
#   语言检验
    if lang != 'en' and lang != 'zh':
        return render_to_response('404.html', {'error': 'Unkown language error'})
#   过滤Draft
    news_list = list(News.objects.filter(news_status=False))

#   获取今天以前的时间：
#   由于DateTimeField有tzinfo，所以无法直接比较，此处可想办法优化
    datetime_now = datetime.datetime.now()
    for i in range(0, len(news_list)):
        datetime_tmp = news_list[i].news_datetime
        datetime_tmp = datetime.datetime.combine(datetime_tmp.date(), datetime_tmp.time()) + datetime.timedelta(hours=8)
        if datetime_tmp < datetime_now:
            news_list = news_list[i:]
            break

#   参数为空，将news_id置为最近的一篇id
    if news_id is None:
        try:
            news_id = news_list[0].id
        except IndexError:      #   news_list为空，返回
            return render_to_response('news.html', {
                'current_item': 'news',
                'lang': lang, 
                'head_group_list': head_group(),
                'url_en': '/en/news',
                'url_zh': '/zh/news'})
        except:
            return render_to_response('404.html')   # 未知错误
#   参数不合法时返回404页面
    try:
        news_id = int(news_id)
    except KeyError:
        return render_to_response('404.html', {'error': 'Invalid newsid'}) 
    except:
        return render_to_response('404.html')

#   返回最近MAX_ITEMS篇文章
    try:
        news_select = News.objects.get(id=news_id)
    except ObjectDoesNotExist:
        return render_to_response('404.html', {'error': 'Page not found'})
    except:
        return render_to_response('404.html')
    location = news_list.index(news_select)
    begin = location / MAX_ITEMS * MAX_ITEMS
    end = min(begin+MAX_ITEMS, len(news_list))
    newslist = news_list[begin:end]
    previd = nextid = None
    if begin > 0:
        previd = news_list[begin-MAX_ITEMS].id
    if end < len(news_list):
        nextid = news_list[end].id
    news_id = str(news_id)
    if lang == 'en':
        return render_to_response('news.html', {
            'current_item': 'news',
            'lang': lang,
            'url_en': '/en/news/'+news_id,
            'url_zh': '/zh/news/'+news_id,
            'head_group_list': head_group(),
            'news_list': newslist, 
            'news_title': news_select.news_title_en,
            'news_id': news_select.id,
            'news_datetime': (news_select.news_datetime + datetime.timedelta(hours=8)).strftime("%Y-%m-%d %H:%M"),
            'news_content': news_select.news_content_en, 
            'news_previd': previd, 'news_nextid': nextid})
    if lang == 'zh':
        return render_to_response('news.html', {
            'current_item': 'news',
            'lang': lang,
            'url_en': '/en/news/'+news_id,
            'url_zh': '/zh/news/'+news_id,
            'head_group_list': head_group(),
            'news_list': newslist, 
            'news_title': news_select.news_title_zh,
            'news_id': news_select.id,
            'news_datetime': (news_select.news_datetime + datetime.timedelta(hours=8)).strftime("%Y-%m-%d %H:%M"),
            'news_content': news_select.news_content_zh, 
            'news_previd': previd, 'news_nextid': nextid})
